<?php

namespace App\Http\Controllers;

use App\Models\Answer;
use App\Models\Question;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;

class ScoreController extends Controller
{
    public function index(Request $request)
    {
        /** @var User $user 考生 */
        $user = Auth::user();

        // 进行中的考试
        $test = $user->currentTest();

        if ($test) {
            // 正在进行中的考试未答完，返回答题页
            // if ($test->question_count > $test->answer()->count()) {
            //     return redirect()->route('test');
            // }

            // 交卷
            $test = $test->submit();
        } else {
            // 没有进行中的考试时，获取最后一次考试
            $test = $user->test()->whereNotNull('submit_at')->latest()->first();

            // 一次考试都没有时，返回首页
            if (! $test) {
                return redirect()->route('home');
            }
        }

        // 获取考试错题
        $questions = collect();
        if (! $test->is_all_right) {
            // 用户提交的答案
            $answers = $test->answer->keyBy('question_id');

            // 本次考试未作答或答错的题目
            $testQuestions = Question::query()
                ->whereIn('id', $test->questions)                               // 考试题目 ID
                ->whereNotIn('id', $answers->where('is_right', true)->keys())   // 答对题目 ID
                ->get()
                ->keyBy('id');

            // 按生成时的随机顺序排列，并填充已选答案
            $questions = collect($test->questions)
                ->reduce(function (Collection $carry, $id) use ($testQuestions, $answers) {
                    /** @var Question $question */
                    if ($question = $testQuestions->get($id)) {
                        /** @var Answer $answer */
                        $answer = $answers->get($id);

                        $question->setAttribute('user_answer', $answer ? $answer->answer : []);

                        return $carry->push($question);
                    } else {
                        return $carry;
                    }
                }, $questions);
        }

        return view('score', compact('user', 'test', 'questions'));
    }
}
